<!-- 数据权限 -->
<template>
  <div class="ky-container">
    <div class="left-content">
      <el-card shadow="hover" class="ky-card ky-card-sx ky-card-hdbg">
        <el-form ref="formSearch" :model="formData" :inline="true" class="ky-form-inline ky-form-inline-sm" label-width="83px">
          <el-form-item label="医院名称" prop="hospitalCode">
            <el-select
              size="small"
              class="param-type_input"
              filterable
              clearable
              v-model="formData.hospitalCode"
              placeholder="请选择"
              @change="hospitalChange">
              <el-option
                v-for="(item,index) in mx_hospitalList"
                :key="index"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科室名称" prop="deptCode">
            <el-select size="small" class="param-type_input" clearable v-model="formData.deptCode" placeholder="请选择">
              <el-option
                v-for="(item,index) in deptCodeList"
                :key="index"
                :label="item.departmentName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" prop="userPhone">
            <el-input v-model="formData.userPhone"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="formData.userName"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="userCode">
            <el-input v-model="formData.userCode"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="m-l-0 click-button" size="small" icon="el-icon-search" @click="search">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="hover" class="ky-card ky-card-hdbg ky-mt10">
        <el-table
          ref="table"
          v-loading="loading"
          size="medium"
          :data="tableData"
          style="width: 100%"
          max-height="578px"
          border
          class="ky-table"
          highlight-current-row
          @row-click="bindData"
        >
          <el-table-column align="left" label="操作" width="80">
            <template slot-scope="scope">
              <div class="flex flex-row justify-center text-center">
                <el-button type="primary" size="small" @click.stop="bindData( scope.row)">权限</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column type="index" label="No."></el-table-column>
          <el-table-column align="left" prop="hospitalName" label="医院名称" min-width="140" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="deptName" label="科室" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="userName" label="姓名" min-width="140" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="userCode" label="账号" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="sex" label="性别" :formatter="sexFormatter"></el-table-column>
          <el-table-column align="left" prop="userPhone" label="手机号" min-width="120"></el-table-column>
          <el-table-column align="left" prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === 1 ? 'success' : 'danger'"
                disable-transitions>{{scope.row.status === 1 ? '启用':'禁用'}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="createTime" label="添加时间" min-width="160"></el-table-column>
          <el-table-column align="left" prop="updateTime" label="更新时间" min-width="160"></el-table-column>
        </el-table>
        <paginationCont
          :total="totalCount"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="changePagination"
        />
      </el-card>
    </div>
    <div class="right-content">
      <el-card shadow="hover" class="ky-card ky-card-sm ky-card-hdbg">
        <div slot="header">数据权限{{currentRow?'【'+currentRow.userName+'】':''}}</div>
        <el-tree
          v-if="!roleAdmin"
          v-loading="rightLoading"
          ref="tree"
          :props="props"
          :data="treeNode"
          show-checkbox
          node-key="key"
          default-expand-all
        >
        </el-tree>
        <div v-else class="tree_role_admin">{{roleAdminMsg}}</div>
        <div class="divide-line" v-show="treeNode.length>0">
          <el-button type="primary" size="small" @click="save">保存</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getDeptList, getUsersPage, getUserhospitalcheckroom, setUserdataauthority, getUserdataauthority } from '@/api/api.js'
import paginationCont from '@/components/Pagination/index'
import dealTreeUtil from '@/utils/dealTreeUtil.js'
export default {
  name: '',
  mixins: [],
  components: { paginationCont },
  data() {
    return {
      currentRow: null,
      formData: {
        hospitalCode: this.$store.state.user.hospitalCode || '',
        deptCode: '',
        userPhone: '',
        userName: '',
        userCode: ''
      },
      deptCodeList: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      loading: false,
      tableData: [],
      rightLoading: false,
      props: {
        label: 'name',
        children: 'children'
      },
      treeNode: [],
      roleAdmin: false,
      roleAdminMsg: ''
    }
  },
  watch: {},
  computed: {},
  created() {
    this.$getHospitalList()
    this.getDeptCodeList()
    this.search()
  },
  mounted() {

  },
  methods: {
    sexFormatter(row, column, cellValue, index) {
      let sexName = ''
      if (row.sex === 0) {
        sexName = '其他'
      } else if (row.sex === 1) {
        sexName = '男'
      } else if (row.sex === 2) {
        sexName = '女'
      }
      return sexName
    },
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      this.treeNode = []
      this.currentRow = null
      this.loading = true
      let params = {
        ...this.formData,
        pageNumber: this.currentPage,
        pageSize: this.pageSize
      }
      getUsersPage(params).then((res) => {
        this.loading = false
        if (res && res.code == 10000) {
          this.tableData = res.content.list
          this.totalCount = res.content.totalCount
        }
      })
    },
    hospitalChange() {
      this.formData.deptCode = ''
      this.getDeptCodeList()
    },
    getDeptCodeList() {
      if (this.formData.hospitalCode) {
        getDeptList({ HospitalCode: this.formData.hospitalCode }).then((res) => {
          if (res && res.code === 10000) {
            this.deptCodeList = res.content.list
          }
        })
      } else {
        this.deptCodeList = []
      }
    },
    bindData(row) {
      this.currentRow = row
      this.rightLoading = true
      this.$refs.table.setCurrentRow(row)
      Promise.all([this.getTree(row), this.getTreeData(row)]).then(() => {
        this.rightLoading = false
      }).catch(() => {
        this.rightLoading = false
      })
    },
    changePagination() {
      this.fetchData()
    },
    handleCheckChange() {

    },
    getTree(row) {
      return new Promise((rs, rj) => {
        this.treeNode = []
        getUserhospitalcheckroom({ sysUserId: row.id }).then((res) => {
          if (res && res.code == 10000) {
            let changeList = [
              { key: 'depAreaCheckRooms', value: 'children' },
              { key: 'depCheckRooms', value: 'children' },
              { key: 'modalityCheckRooms', value: 'children' },
              { key: 'hospitalName', value: 'name' },
              { key: 'depArea', value: 'name' },
              { key: 'dep', value: 'name' },
              { key: 'modality', value: 'name' }
            ]
            this.treeNode = dealTreeUtil.copyTransFunc(res.content.list, changeList)
            this.dealTree(this.treeNode)
          }
          rs()
        }).catch(() => {
          rj()
        })
      })
    },
    getTreeData(row) {
      return new Promise((rs, rj) => {
        this.roleAdmin = false
        getUserdataauthority({ SysUserId: this.currentRow.id }).then((res) => {
          if (res && res.code === 10000) {
            let list = res.content.list
            let keys = []
            list.forEach(e => {
              let k = e.hospitalCode
              if (e.depArea) {
                k = k + '-' + e.depArea
              }
              if (e.dep) {
                k = k + '-' + e.dep
              }
              if (e.modality) {
                k = k + '-' + e.modality
              }
              keys.push(k)
            })
            this.$refs.tree.setCheckedKeys(keys)
          } else if (res.code === 10001) {
            this.roleAdmin = true
            this.roleAdminMsg = res.message
          }
          rs()
        }).catch(() => {
          rj()
        })
      })
    },
    dealTree(arr, key) {
      arr.forEach((item) => {
        if (!key) {
          item.key = item.hospitalCode
        } else {
          item.key = key + '-' + item.name
        }
        if (item.children && item.children.length) {
          this.dealTree(item.children, item.key)
        }
      })
    },
    save() {
      let keys = this.$refs.tree.getCheckedKeys()
      let savedKeys = [] // 将被保存的key
      let arr = []
      keys.forEach(k => {
        let flag = true
        for (let sk of savedKeys) {
          if (k.indexOf(sk) > -1) { // 比较是否有父级被保存过-父级被保存过这一级就不给保存了
            flag = false
            return
          }
        }
        if (flag) {
          savedKeys.push(k)
          let obj = {
            hospitalCode: k.split('-')[0],
            depArea: k.split('-')[1],
            dep: k.split('-')[2],
            modality: k.split('-')[3]
          }
          arr.push(obj)
        }
      })
      this.rightLoading = true
      setUserdataauthority({ sysUserId: this.currentRow.id, list: arr }).then((res) => {
        this.rightLoading = false
        if (res && res.code) {
          this.$message.success('保存成功')
        }
      }).catch(() => {
        this.rightLoading = false
      })
    }
  },
  beforeDestroy() {},
  destroyed() {},
  beforeUpdate() {},
  updated() {}
}
</script>
<style lang='scss' scoped>
.ky-container{
    .left-content{
        width: calc(100% - 360px);
        float: left;
    }
    .right-content{
        width: 350px;
        float: left;
        margin-left: 10px;
        .el-tree{
            height: calc(100vh - 192px);
            overflow-y: auto;
        }
        .ky-card{
            height: 100%;
        }
        .divide-line{
            width:100%;
            border-top: 1px solid #e5e5e5;
            min-height: 40px;
            padding-top: 10px;
            text-align: right;
        }
    }
    .tree_role_admin{
      height: calc(100vh - 192px);
      display: flex;
      align-items: center;
      justify-content: center;
    }
}
.ky-form-inline-sm .el-form-item /deep/ .el-input__inner{
    width: 220px;
}
</style>
